import { store } from "../redux/store"
import { useQuery } from '@realm/react'
import { schemaName } from "../realm"
let URLAPI = 'https://tweetwallet.io/api';
let URLUPLOAD = 'https://home.tweetwallet.io/upapi';
let URLUWSAPI = 'https://tweetwallet.io/wsapi';


function to(promise) {
    return promise
        .then((data) => {
            if (data.code == 1006) {
                store.dispatch((dispatch) => {
                    dispatch({ type: 'app/setIsLogin', payload: true })
                })
            }
            return [null, data];
        })
        .catch((err) => [err]);
}
function returnErr(err) {
    return Object.assign(err, {
        status: "406",
        description: err.errMsg
    }, true);
}

const header = {
    // "Content-type": "multipart/form-data"
}
const token_type = "Bearer"
const formData = (params) => {
    let formData = new FormData();
    for (let i in params) {
        formData.append(i, params[i])
    }
    return formData
}

const httpApi2 = () => {
    const Token = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true')
    })[0]?.Token;
    const http = {
        get(url, params) {
            if (params) {
                let paramsArray = [];
                Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
                if (url.search(/\?/) === -1) {
                    url += '?' + paramsArray.join('&')
                } else {
                    url += '&' + paramsArray.join('&')
                }
            }
            const { app } = store.getState()
            if (app.token) {
                header.Authorization = token_type + ' ' + app.token
            }
            return new Promise(function (resolve, reject) {
                fetch(URLAPI + url, { headers: header })
                    .then((response) => response.json()
                    )
                    .then((responseData) => {
                        resolve(responseData);
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        },
        async post(url, params) {
            return new Promise(async function (resolve, reject) {
                if (Token) {
                    header.Authorization = token_type + ' ' + Token
                }
                fetch(URLAPI + url, {
                    method: 'POST',
                    headers: header,
                    body: formData(params)  //body参数，通常需要转换成字符串后服务器才能解析
                }).then((response) => response.json())
                    .then((responseData) => {
                        resolve(responseData);
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        },
        async wsapiPost(url, params) {
            return new Promise(async function (resolve, reject) {
                const { app } = store.getState()
                if (app.token) {
                    header.Authorization = token_type + ' ' + app.token
                }
                fetch(URLUWSAPI + url, {
                    method: 'POST',
                    headers: header,
                    body: formData(params)  //body参数，通常需要转换成字符串后服务器才能解析
                }).then((response) => response.json())
                    .then((responseData) => {
                        resolve(responseData);
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        },
        wsapiGet(url, params) {
            if (params) {
                let paramsArray = [];
                //拼接参数
                Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
                if (url.search(/\?/) === -1) {
                    url += '?' + paramsArray.join('&')
                } else {
                    url += '&' + paramsArray.join('&')
                }
            }
            const { app } = store.getState()
            if (app.token) {
                header.Authorization = token_type + ' ' + app.token
            }
            return new Promise(function (resolve, reject) {
                fetch(URLUWSAPI + url, { headers: header })
                    .then((response) => response.json()
                        //将返回数据转化为json，也可以转为text(),否则无法看到返回数据,且必须回调才可以看到
                    )
                    .then((responseData) => {
                        resolve(responseData);
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        },
        async upload(url, params) {
            return new Promise(async function (resolve, reject) {
                const { app } = store.getState()
                if (app.token) {
                    header.Authorization = token_type + ' ' + app.token
                }
                const formData = new FormData()
                if (params instanceof Array) {
                    for (let index = 0; index < params.length; index++) {
                        const element = params[index];
                        let uri = element.uri
                        let uriArr = uri.split('/')
                        let name = uriArr[uriArr.length - 1]
                        formData.append('f', {
                            uri,
                            name: element.fileName || name,
                            type: element.type,
                        })
                    }
                } else {
                    let uriArr = params.uri.split('/')
                    let name = uriArr[uriArr.length - 1]
                    formData.append('f', {
                        uri: params.uri,
                        name: params.fileName || name,
                        type: params.type,
                    })
                }

                fetch(URLUPLOAD + url, {
                    method: 'POST',
                    headers: header,
                    body: formData  //body参数，通常需要转换成字符串后服务器才能解析
                }).then((response) => response.json())
                    .then((responseData) => {
                        resolve(responseData);
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        },
    };

    const setUserNickName = async (params) => {
        const url = '/setUserNickName';
        const [err, res] = await to(http.post(url, params));
        if (err) {
            return returnErr(err)
        }
        return res;
    }
    return {
        setUserNickName
    }
}

export default httpApi2